package com.yl.immodule;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.android.yl.ylicpsdk.ICPRtc;
import com.android.yl.ylicpsdk.ICPRtcEventHandler;
import com.android.yl.ylicpsdk.ICPRtcManager;
import com.camera.base.Log.YLogImpl;
import com.camera.base.bean.BaseUser;
import com.camera.base.inerface.FileUploadListener;
import com.camera.base.inerface.ICPInterface;
import com.camera.base.inerface.WebModelFactory;
import com.camera.base.net.api.ApiServiceEntryPoint;
import com.camera.base.net.listener.NetInterface;
import com.camera.base.net.response.AuthResponse;
import com.camera.base.util.DefaultWebModelFactory;
import com.camera.base.util.YLIMConfig;
import com.camera.base.wbmodels.WebModel;
import com.camera.base.wbmodels.WebSocketCode;
import com.camera.routemodule.RouterPath;
import com.camera.routemodule.routeinterface.IMAppInterface;
import com.camera.routemodule.routeinterface.RouterUtil;
import com.camera.routemodule.routeinterface.YLWebSocketInterface;
import com.google.gson.Gson;
import com.hm.poc.IPocEngineEventHandler;
import com.hm.poc.OnFileUploadListener;
import com.hm.poc.chat.ChatMessageCategory;
import com.hm.poc.chat.ChatMessageStatus;
import com.hm.poc.chat.ChatUtil;
import com.hm.poc.common.TempChannel;
import com.hm.poc.http.HttpCallback;
import com.hm.poc.http.HttpSenderManager;
import com.unionbroad.greendao.Channel;
import com.unionbroad.greendao.ChatMessage;
import com.unionbroad.greendao.ChatMessageDBHelper;
import com.unionbroad.greendao.MessageDialogue;
import com.unionbroad.greendao.MessageDialogueDBHelper;
import com.unionbroad.greendao.User;
import com.unionbroad.app.eventbus.ChannelChangedEvent;
import com.unionbroad.app.util.FileDownloadManager;
import com.yl.immodule.cc.CCHelper;
import com.yl.immodule.util.MeetManger;
import com.yl.immodule.util.MonitorVideoHelper;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import dagger.hilt.android.EntryPointAccessors;

@Route(path = RouterPath.path.im_manager)
public class IMAppManager implements IMAppInterface {
    private final static String TAG = IMAppManager.class.getSimpleName();
    private Application application;
    private WebModelFactory mWebModelFactory  = new DefaultWebModelFactory();
    private ICPRtcEventHandler.IncomingInfo currentCallInfo;
    public YLWebSocketInterface mYLWebSocketInterface;
    public MonitorVideoHelper monitorVideoHelper = null;
    private BaseUser mCurBaseUser;
    public WebModel speakWebModel;
    public final String PREFS_NAME = "file_config";
    public ICPInterface icpInterface;
    private NetInterface netInterface;
    public String authToken = "";
    @Override
    public void init(Context context) {

    }
    @Override
    public void init(@NonNull Application application,ICPInterface icpInterface) {
        IMVERSION.Companion.setIMVersion(IMVERSION_.V2);
        this.application = application;
        this.icpInterface = icpInterface;
        ICPRtcManager.init(application,getConfig());
        ICPRtcManager.getsInstance().addEventHandler(mIcpRtcEventHandler);
        initNetInterface();
    }
    private void initNetInterface() {
        try {
            ApiServiceEntryPoint entryPoint = EntryPointAccessors.fromApplication(
                application.getApplicationContext(),
                ApiServiceEntryPoint.class
            );
            netInterface = entryPoint.getNetInterface();
            Log.d(TAG, "NetInterface 初始化成功");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    netInterface.reqAuthBySdkKey(AuthResponse.class, new HttpCallback<AuthResponse>() {
                        @Override
                        public void onResult(AuthResponse authResponse) {
                            if (authResponse.getCode() == 200){
                                authToken = authResponse.getData().getAccessToken();
                            }
//                            Log.e(TAG, "netInterface: "+authResponse.getCode()+"  "+authResponse.getData().getAccessToken() );
                        }
                    });
                }
            }).start();

        } catch (Exception e) {
            Log.e(TAG, "NetInterface 初始化失败: " + e.getMessage(), e);
        }
    }
    @Override
    public void reInitEngine() {
        ICPRtcManager.reInitFactory(getConfig());
//        ICPRtcManager.init(application,getConfig());
        ICPRtcManager.getsInstance().addEventHandler(mIcpRtcEventHandler);
    }
    public void setIPParams(String ip,String sipPort,String httpPort) {
        ICPRtc.Configure configure = ICPRtcManager.getsInstance().getConfig();
        configure.ip = ip;
        configure.port = sipPort;
        configure.httpPort = httpPort;
        ICPRtcManager.getsInstance().config(configure);
    }
    @Override
    public  ICPRtc.Configure getConfig() {
        ICPRtc.Configure configure = ICPRtcProducer.getConfig();

        configure.ip = YLIMConfig.ip;
        configure.port = YLIMConfig.sipProt;
        configure.httpPort = YLIMConfig.httpProt;

        /** 可选配置 */
        //使用音乐通道
        configure.useMusicStream = false;
        configure.useHttps = false;
        //对讲录音
        configure.pttPlayback = true;

        //AI降噪
        configure.aiNoiseSuppression = false;

        //保活服务
        configure.keepLiveService = true;
        configure.keepLiveHeartbeat = 600;

        //联系人状态刷新时间间隔，单位秒
        configure.statusUpdateInterval = 120;

        configure.useExternalCamera = false;
        configure.useExternalCamera_V4l2 = false;
        //禁用SDK定位，只在第一次初始化时有效，后边再更改这个值不生效
        configure.disableInternalGpsFunc = true;
//        //上报自己的位置信息，定时上报，使用者自己确定 定位模式 以及 上报间隔
//        mPocEngine.reportLocationChange(String longitude, String latitude, String altitude)

        configure.externalEncodeFrame = false;//外部推流这个视频+音频

        Log.e(TAG, "getConfig: 是否是h265:"+icpInterface.getVideoDecoderType());
        if (icpInterface.getVideoDecoderType()){
            configure.extHardwareEncodeH265 = true;
            configure.extHardwareEncodeH264 = false;
        }else{
            configure.extHardwareEncodeH264 = true;
            configure.extHardwareEncodeH265 = false;
        }

        configure.externalFrameConsumer = false;

        //视频通话分辨率，需要和调度台中设置的值一样才能生效
        //渲染模式
        configure.videoRenderMode = ICPRtcEventHandler.VideoViewRenderMode.RENDER_MODE_ASPECT_FIT;

        configure.enableSoundTip = false;
        /*
        configure.useMusicStream = false;
        configure.audioAecLevel = ICPRtcEventHandler.AudioAecLevel.AEC_LEVEL_3;
        configure.audioAgcLevel = ICPRtcEventHandler.AudioAgcLevel.AGC_LEVEL_0;
        configure.audioNsLevel = ICPRtcEventHandler.AudioNsLevel.NS_LEVEL_3;
        if ("p999-xd".equals(Build.MODEL)) {
            //手持终端
            configure.audioSource = MediaRecorder.AudioSource.VOICE_COMMUNICATION;
        } else {
            //pad
            configure.audioSource = MediaRecorder.AudioSource.VOICE_COMMUNICATION;
            configure.pttAudioSource = MediaRecorder.AudioSource.MIC;
        }*/

        if (Build.MODEL.equalsIgnoreCase("cpu: mt6771 8 core 2.0ghz ram: 4g rom: 16g")) {
            configure.audioAecLevel = ICPRtcEventHandler.AudioAecLevel.AEC_LEVEL_2;
            configure.audioAgcLevel = ICPRtcEventHandler.AudioAgcLevel.AGC_LEVEL_DEFAULT;
            configure.audioNsLevel = ICPRtcEventHandler.AudioNsLevel.NS_LEVEL_2;
            int mic = MediaRecorder.AudioSource.MIC;
            configure.audioSource = mic;
            configure.pttAudioSource = mic;
            configure.useMusicStream = false;
        }
        configure.videoResolution = ICPRtcEventHandler.VideoResolution.RESOLUTION_640X480;
        configure.defaultFrontCamera = true;
        configure.camera_hal_api_version_1_0 = true;
        configure.frontCameraId = 0;

        configure.hardwareEncode = false;
        //缓存提供器，没特殊要求用不到
        //configure.cacheFileSupplier = cacheFileSupplier;
        //侧边功能键注册，一般都用不到
        //configure.broadcastHotKeyActionSupplier = hotKeyActionSupplier;
        //其它...
        return configure;
    }

    @Override
    public void setWebSocketServer(@NonNull YLWebSocketInterface mYLWebSocketInterface) {
        this.mYLWebSocketInterface = mYLWebSocketInterface;
        MeetManger.getInstance().setWebSocketServer(mYLWebSocketInterface);
        IMApplocation.getInstance().setWebSocketServer(mYLWebSocketInterface);
    }

    @Override
    public void login(@NonNull String acc, @NonNull String pws) {
        netInterface.reqAuthBySdkKey(AuthResponse.class, new HttpCallback<AuthResponse>() {
            @Override
            public void onResult(AuthResponse authResponse) {
                Log.e(TAG, "onResult: "+authResponse.getCode()+"  "+authResponse.getData().getAccessToken() );
            }
        });
        ICPRtcManager.getsInstance().addEventHandler(icpRtcEventHandlerLogin);
        ICPRtcManager.getsInstance().login(acc, pws);
    }

    public BaseUser getCurrentUser() {
        if (mCurBaseUser == null) {
            mCurBaseUser = new BaseUser();
        }
        mCurBaseUser.setIconUrl(ICPRtcManager.getsInstance().getCurrentUser().getIconUrl());
        mCurBaseUser.setName(ICPRtcManager.getsInstance().getCurrentUser().getName());
        mCurBaseUser.setType(ICPRtcManager.getsInstance().getCurrentUser().getType());
        mCurBaseUser.setNumber(ICPRtcManager.getsInstance().getCurrentUser().getNumber());
        mCurBaseUser.setStatus(ICPRtcManager.getsInstance().getCurrentUser().getStatus());
        mCurBaseUser.setUid(ICPRtcManager.getsInstance().getCurrentUser().getUid());
        return mCurBaseUser;
    }
    ICPRtcEventHandler icpRtcEventHandlerLogin = new ICPRtcEventHandler() {
        @Override
        public void onLoginStepProgress(int progress, String msg) {
            WebModel webModel2 = null;
            if (mYLWebSocketInterface != null) {
                if (progress ==  LoginProgress.PRO_LOGIN_SUCCESS
                        || progress ==  LoginProgress.PRO_BINDING_ACCOUNT_FAILED
                        || progress ==  LoginProgress.PRO_BINDING_ACCOUNT_NOT_EXIST
                        || progress ==  LoginProgress.PRO_BINDING_ACCOUNT_NOT_ACTIVE
                        || progress ==  LoginProgress.PRO_LOGIN_FAILED){
                    webModel2 = mWebModelFactory.createResultWebModelIM("login");
                }
            }
            if (progress == LoginProgress.PRO_LOGIN_SUCCESS) {
                if (webModel2 != null) {
                    webModel2.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_LOGIN_SUC);
                    List<User> users =  ICPRtcManager.getsInstance().getUserList();
                    webModel2.getiMWebModel().getImResultConfig().setUsers(users);
                    List<MessageDialogue> messageDialogueArray = ICPRtcManager.getsInstance().getAllConversation();
                    webModel2.getiMWebModel().getImResultConfig().setChats(messageDialogueArray);
                    webModel2.getiMWebModel().getImResultConfig().setToken(HttpSenderManager.INSTANCE.getToken());
                    webModel2.getiMWebModel().getImResultConfig().setAuth(authToken);
                }
                ICPRtcManager.getsInstance().removeEventHandler(icpRtcEventHandlerLogin);
                Intent intentSuc = new Intent("login_success");
                intentSuc.addFlags(0x01000000);
//                intentSuc.setPackage("com.icp.demo");
                application.sendBroadcast(intentSuc);
            } else if (progress == LoginProgress.PRO_BINDING_ACCOUNT_FAILED) {
                if (webModel2 != null) {
                    webModel2.getiMWebModel().getImResultConfig().setCode(2);
                }
                Toast.makeText(application, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            } else if (progress == LoginProgress.PRO_BINDING_ACCOUNT_NOT_EXIST) {
                if (webModel2 != null) {
                    webModel2.getiMWebModel().getImResultConfig().setCode(3);
                }
                Toast.makeText(application, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            } else if (progress == LoginProgress.PRO_BINDING_ACCOUNT_NOT_ACTIVE) {
                if (webModel2 != null) {
                    webModel2.getiMWebModel().getImResultConfig().setCode(4);
                }
                Toast.makeText(application, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            } else if (progress == LoginProgress.PRO_LOGIN_FAILED) {
                if (webModel2 != null) {
                    webModel2.getiMWebModel().getImResultConfig().setCode(5);
                }
                Toast.makeText(application, "Login failed " + msg, Toast.LENGTH_SHORT).show();
            }
            if (webModel2 != null){
                String jsonString = new Gson().toJson(webModel2);
                mYLWebSocketInterface.sendMessage(jsonString);//返回用户列表 以及 聊天室列表
            }
        }
    };

    @Override
    public void getWebSocketApi(@NonNull WebModel mWebModel) {
        if (mYLWebSocketInterface != null){
            Log.e("TAG", "onWebSocketMeesage: "+mWebModel.toString() );
            if (mWebModel.getiMWebModel().getAbility().equals("set_http_config")) {
//                    mWebModel.getiMWebModel().getPocConfig().getIp()
                YLIMConfig.setIp(mWebModel.getiMWebModel().getPocConfig().getIp());
                YLIMConfig.setSipProt(mWebModel.getiMWebModel().getPocConfig().getProt()+"");
                YLIMConfig.setHttpProt(mWebModel.getiMWebModel().getPocConfig().getHttpProt()+"");
                RouterUtil.INSTANCE.getIMManagerImpl().reInitEngine();

            }else  if (mWebModel.getiMWebModel().getAbility().equals("login")) {
                login(mWebModel.getiMWebModel().getPocConfig().getAcc(),mWebModel.getiMWebModel().getPocConfig().getPsw());
            }else  if (mWebModel.getiMWebModel().getAbility().equals("audio_call")) {
                ARouter.getInstance()
                        .build(RouterPath.path.av_pop_activity)
                        .withBoolean("isIncomingCall", false)
                        .withString("callerId", mWebModel.getiMWebModel().getPocConfig().getNumber())
                        .withInt("type", ICPRtcEventHandler.SessionType.TYPE_AUDIO_CALL)
                        .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                        .navigation();
            }else  if (mWebModel.getiMWebModel().getAbility().equals("video_call")) {
                ARouter.getInstance()
                        .build(RouterPath.path.av_pop_activity)
                        .withBoolean("isIncomingCall", false)
                        .withString("callerId", mWebModel.getiMWebModel().getPocConfig().getNumber())
                        .withInt("type", ICPRtcEventHandler.SessionType.TYPE_VIDEO_CALL)
                        .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                        .navigation();
            }else  if (mWebModel.getiMWebModel().getAbility().equals("send_message")) {
                YLogImpl.e(TAG,"获取到消息:"+mWebModel.getiMWebModel().getPocConfig().getType());

                ChatMessage message = null;
                long chatid = mWebModel.getiMWebModel().getPocConfig().getChat_id();
                if (mWebModel.getiMWebModel().getPocConfig().getType() == 1) {
                    message = ChatUtil.createOutTextMessage(mWebModel.getiMWebModel().getPocConfig().getText(),chatid);
                }else if (mWebModel.getiMWebModel().getPocConfig().getType() == 3) {
                    message = ChatUtil.createOutAudioMessage("",chatid);
                    message.setHttpFile(mWebModel.getiMWebModel().getPocConfig().getPath());
                }else if (mWebModel.getiMWebModel().getPocConfig().getType() == 2) {
                    message = ChatUtil.createOutImgMessage("",chatid);
                    message.setHttpFile(mWebModel.getiMWebModel().getPocConfig().getPath());
                }else if (mWebModel.getiMWebModel().getPocConfig().getType() == 4) {
                    message = ChatUtil.createOutVideoMessage("",chatid);
                    message.setHttpFile(mWebModel.getiMWebModel().getPocConfig().getPath());
                }else if (mWebModel.getiMWebModel().getPocConfig().getType() == 5) {
                    String[]  jw= mWebModel.getiMWebModel().getPocConfig().getJd_wd().split("_");
                    message = ChatUtil.createOutLocationMessage(jw[0],jw[1],mWebModel.getiMWebModel().getPocConfig().getLocation_desc(),chatid);
                }

                if (message != null){
                    if (mYLWebSocketInterface != null) {
                        WebModel webModel2 = mWebModelFactory.createResultWebModelIM("send_message");
                        webModel2.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_SEND_MSG);
                        webModel2.getiMWebModel().getImResultConfig().setChatMessage(message);
                        String jsonString = new Gson().toJson(webModel2);
                        mYLWebSocketInterface.sendMessage(jsonString);//返回用户列表 以及 聊天室列表
                    }
                    YLogImpl.e(TAG,"发送消息"+chatid+":"+mWebModel.getiMWebModel().getPocConfig().getText());
                    ICPRtcManager.getsInstance().sendMessage(message);
                }
            }else  if (mWebModel.getiMWebModel().getAbility().equals("create_audio_channel")) {
                String userString = mWebModel.getiMWebModel().getPocConfig().getUsers();
                String[] users = userString.split(",");
                List<User> userLists = ICPRtcManager.getsInstance().getUserList();
                List<User> userAdds = new ArrayList<>();
                for (String u:users) {
                    for (User a:userLists){
                        if (u.equals(a.getNumber()+"")) {
                            userAdds.add(a);
                        }
                    }
                }
                if (userAdds.size() > 0){
                    ICPRtcManager.getsInstance().createAudioPTTChannel(mWebModel.getiMWebModel().getPocConfig().getChannel_name(), userAdds, new ICPRtcEventHandler.Callback<Channel>() {
                        @Override
                        public void onResponse(final Channel channel) {
                            if (channel != null){
                                WebModel webModel = mWebModelFactory.createResultWebModelIM("create_audio_channel");
                                webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_CREATE_CHANNEL);
                                webModel.getiMWebModel().getImResultConfig().setChannelId(channel.getCid());
                                webModel.getiMWebModel().getImResultConfig().setChannelNumber(channel.getChannelNumber());
                                String jsonString = new Gson().toJson(webModel);
                                mYLWebSocketInterface.sendMessage(jsonString);

                            }
                            List<Channel> channelList = ICPRtcManager.getsInstance().getAudioPttChannelList();
                            for (Channel a:channelList){
                                Log.e(TAG, "{\"foctory\":  "+a.getChannelNumber());
                            }
                        }
                    });
                }

            }else  if (mWebModel.getiMWebModel().getAbility().equals("create_audio_temp_channel")) {
                Log.e(TAG, "创建临时对讲组: ");
                String userString = mWebModel.getiMWebModel().getPocConfig().getUsers();
                String[] users = userString.split(",");
                List<User> userLists = ICPRtcManager.getsInstance().getUserList();
                List<User> userAdds = new ArrayList<>();
                for (String u:users) {
                    for (User a:userLists){
                        if (u.equals(a.getNumber()+"")) {
                            Log.e(TAG, "websocket:创建临时对讲组 :"+ a.getNumber());
                            userAdds.add(a);
                        }
                    }
                }
                if (userAdds.size() > 0){
                    TempChannel tempChannel = ICPRtcManager.getsInstance().createTempAudioPTTChannel(userAdds);
                    if (tempChannel != null){
                        WebModel webModel = mWebModelFactory.createResultWebModelIM("create_audio_temp_channel");
                        webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_CREATE_TRMP_CHANNEL);
                        webModel.getiMWebModel().getImResultConfig().setChannelId(tempChannel.getChannelNumber()+"");
                        webModel.getiMWebModel().getImResultConfig().setChannelNumber(tempChannel.getChannelNumber());
                        String jsonString = new Gson().toJson(webModel);
                        mYLWebSocketInterface.sendMessage(jsonString);
                    }

                }
            }else if (mWebModel.getiMWebModel().getAbility().equals("join_audio_channel")){
                boolean state = ICPRtcManager.getsInstance().joinChannel(mWebModel.getiMWebModel().getPocConfig().getChannelNumber() + "");
                WebModel webModel = mWebModelFactory.createResultWebModelIM("join_audio_channel");
                webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_JOIN_CHANNEL);
                webModel.getiMWebModel().getImResultConfig().setStatus(state);
                webModel.getiMWebModel().getImResultConfig().setChannelNumber(mWebModel.getiMWebModel().getPocConfig().getChannelNumber());
                String jsonString = new Gson().toJson(webModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }else if (mWebModel.getiMWebModel().getAbility().equals("remove_audio_channel")){
                ICPRtcManager.getsInstance().removeAudioPTTChannel(mWebModel.getiMWebModel().getPocConfig().getChannelNumber(), new ICPRtcEventHandler.Callback<Boolean>() {
                    @Override
                    public void onResponse(Boolean aBoolean) {
                        WebModel webModel = mWebModelFactory.createResultWebModelIM("remove_audio_channel");
                        webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_REMOVE_CHANNEL);
                        webModel.getiMWebModel().getImResultConfig().setStatus(aBoolean);
                        String jsonString = new Gson().toJson(webModel);
                        mYLWebSocketInterface.sendMessage(jsonString);
                    }
                });
            }else if (mWebModel.getiMWebModel().getAbility().equals("leave_audio_channel")){
                boolean state = ICPRtcManager.getsInstance().leaveChannel(mWebModel.getiMWebModel().getPocConfig().getChannelNumber()+"");
                WebModel webModel = mWebModelFactory.createResultWebModelIM("leave_audio_channel");
                webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_LEAVE_CHANNEL);
                webModel.getiMWebModel().getImResultConfig().setStatus(state);
                webModel.getiMWebModel().getImResultConfig().setChannelNumber(mWebModel.getiMWebModel().getPocConfig().getChannelNumber());
                String jsonString = new Gson().toJson(webModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }else if (mWebModel.getiMWebModel().getAbility().equals("apply_ptt_speak")){
                Log.e(TAG, "getWebSocketApi: "+11111 );
                ICPRtcManager.getsInstance().applyPttSpeak();
            }else if (mWebModel.getiMWebModel().getAbility().equals("free_ptt_speak")){
                ICPRtcManager.getsInstance().freePttSpeak();
            }else if (mWebModel.getiMWebModel().getAbility().equals("get_message_unread_count")){
                int count = ICPRtcManager.getsInstance().getUnReadMsgCount(mWebModel.getiMWebModel().getPocConfig().getChat_id());

                WebModel webModel = mWebModelFactory.createResultWebModelIM("get_message_unread_count");
                webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_MSG_COUNT_FOR_CHAT);
                webModel.getiMWebModel().getImResultConfig().setCount(count);
                webModel.getiMWebModel().getImResultConfig().setChatId(mWebModel.getiMWebModel().getPocConfig().getChat_id());
                String jsonString = new Gson().toJson(webModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            } if (mWebModel.getiMWebModel().getAbility().equals("get_allmessage_for_chat")){
                WebModel webModel = mWebModelFactory.createResultWebModelIM("get_allmessage_for_chat");
                List<MessageDialogue> messageDialogueArray = new ArrayList<>();
                List<ChatMessage> chatMessages = new ArrayList<ChatMessage>();
                if (mWebModel.getiMWebModel().getPocConfig().getChat_id() == 0){
                    messageDialogueArray.addAll(ICPRtcManager.getsInstance().getAllConversation());
                    webModel.getiMWebModel().getImResultConfig().setChats(messageDialogueArray);
                    webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_ALL_MSG_FOR_CHAT);
                    webModel.getiMWebModel().getImResultConfig().setStatus(false);
                    for (MessageDialogue messageDialogue : messageDialogueArray) {
                        List<ChatMessage> chatMessageList = ICPRtcManager.getsInstance().getConversationMessages(messageDialogue.getChat_id());
                        chatMessages.addAll(chatMessageList);
                    }
                }else{
                    chatMessages.addAll(ICPRtcManager.getsInstance().getConversationMessages(mWebModel.getiMWebModel().getPocConfig().getChat_id()));
                    messageDialogueArray.add(ICPRtcManager.getsInstance().getConversation(mWebModel.getiMWebModel().getPocConfig().getChat_id()));
                    webModel.getiMWebModel().getImResultConfig().setChats(messageDialogueArray);
                    webModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_ALL_MSG_FOR_CHAT);
                    webModel.getiMWebModel().getImResultConfig().setStatus(true);
                }
                webModel.getiMWebModel().getImResultConfig().setChatMessage(chatMessages);
                String jsonString = new Gson().toJson(webModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }else if (mWebModel.getiMWebModel().getAbility().equals("av_result")){

                if (mWebModel.getiMWebModel().getAvResultConfig().getCode() == 1010) {
                    String callerID = mWebModel.getiMWebModel().getAvResultConfig().getCallerId();
                    int type = mWebModel.getiMWebModel().getAvResultConfig().getTypeCode();
                    ARouter.getInstance()
                            .build(RouterPath.path.av_pop_activity)
                            .withString("callerId", callerID)
                            .withInt("type", type)
                            .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                            .navigation();
                }else if (mWebModel.getiMWebModel().getAvResultConfig().getCode() == 1008) {
                    MeetManger.getInstance().showRometView();
                }else if (mWebModel.getiMWebModel().getAvResultConfig().getCode() == 1009) {
                    if (mWebModel.getiMWebModel().getAvResultConfig().getTypeCode() == 0) {
                        MeetManger.getInstance().tryAcceptCall();
                    }else{
                        MeetManger.getInstance().tryHangUp();

                    }
                }
            }

        }


    }

    @Override
    public boolean hasServiceConnected() {
        return ICPRtcManager.getsInstance().hasServiceConnected();
    }




    /**
     * 目前配置项较多，很多配置没有单独的设置接口，建议全局保持一个Configure，
     * 确保每次 ICPRtcProducer.get().config()时，设置进去的配置项都是有效值
     */
    public static class ICPRtcProducer {
        static ICPRtc.Configure configure;
        public static ICPRtc.Configure getConfig() {
            if (configure == null) {
                configure = new ICPRtc.Configure();
//                configure.ip = "121.40.230.149";
//                configure.port = "6050";
//                configure.httpPort = "80";

                configure.ip = "112.124.70.138";
                configure.port = "6050";
                configure.httpPort = "80";
                configure.useNewServer = true; //php服务器设置为false, java服务器设置为true

//                configure.ip = "192.168.0.96";
//                configure.port = "80";
//                configure.httpPort = "7080";
            }
            return configure;
        }
    }

    private final ICPRtcEventHandler mIcpRtcEventHandler = new ICPRtcEventHandler() {
        @Override
        public void onNewConversationCreated(MessageDialogue messageDialogue) {
            ////创建了新的会话
            if (mYLWebSocketInterface != null) {
                WebModel webModel2 = mWebModelFactory.createResultWebModelIM("notify_new_chat_room");
                webModel2.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_NEW_CHAT);
                webModel2.getiMWebModel().getImResultConfig().setChats(messageDialogue);
                webModel2.getiMWebModel().getImResultConfig().setStatus(true);
                String jsonString = new Gson().toJson(webModel2);
                mYLWebSocketInterface.sendMessage(jsonString);//返回用户列表 以及 聊天室列表
            }
        }
        @Override
        public void onMessageArrived(ChatMessage message) {
            //消息送达
            Log.d(TAG,"onMessageArrived-> ");
            if (mYLWebSocketInterface != null) {
                WebModel webModel2 = mWebModelFactory.createResultWebModelIM("send_message");
                webModel2.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_SEND_MSG);
                webModel2.getiMWebModel().getImResultConfig().setChatMessage(message);
                webModel2.getiMWebModel().getImResultConfig().setStatus(true);
                String jsonString = new Gson().toJson(webModel2);
                mYLWebSocketInterface.sendMessage(jsonString);//返回用户列表 以及 聊天室列表
            }
        }

        @Override
        public void onMessageSendFailed(ChatMessage message) {
            //消息发送失败
            Log.d(TAG,"onMessageSendFailed-> ");
            if (mYLWebSocketInterface != null) {
                WebModel webModel2 = mWebModelFactory.createResultWebModelIM("send_message");
                webModel2.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_SEND_MSG);
                webModel2.getiMWebModel().getImResultConfig().setChatMessage(message);
                webModel2.getiMWebModel().getImResultConfig().setStatus(false);
                String jsonString = new Gson().toJson(webModel2);
                mYLWebSocketInterface.sendMessage(jsonString);//返回用户列表 以及 聊天室列表
            }

        }
        @Override
        public void onMessageFileSendProgressChanged(ChatMessage message) {
//            if (_chatId.getValue() != null && message.getChat_id() == _chatId.getValue()) {
//                Log.d(TAG, "文件上传进度更新: " + message.getId() + ", 进度: " + message.getUpdown_progress() + "%");
//                updateMessage(message);
//            }
        }
        @Override
        public void onMessageReceived(long chatId, List<ChatMessage> messages) {
            //接收到新消息
            Log.d(TAG,"onMessageReceived-> ");
            if (mYLWebSocketInterface != null) {
                WebModel webModel2 = mWebModelFactory.createResultWebModelIM("send_message");
                webModel2.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_MSG_RECIVER);
                webModel2.getiMWebModel().getImResultConfig().setChatMessage(messages);
                webModel2.getiMWebModel().getImResultConfig().setChatId(chatId);
                String jsonString = new Gson().toJson(webModel2);
                mYLWebSocketInterface.sendMessage(jsonString);//返回用户列表 以及 聊天室列表
            }

            //收到新的消息
            if (messages != null && messages.size() > 0) {
                //仅为调试，只取出其中一条
                ChatMessage message = messages.get(0);
                //语音通话记录
                if (message.getCategory() == ChatMessageCategory.AUDIO) {
                    Log.d("IMAppManager","==> 语音通话记录");
                }
                //视频通话记录
                else if (message.getCategory() == ChatMessageCategory.VIDEO) {
                    Log.i("IMAppManager","==> 视频通话记录");
                }
                //语音广播
                else if (message.getCategory() == ChatMessageCategory.AUDIO_BROADCAST) {
                    Log.i("IMAppManager","==> 语音广播");
                }
                //语音文件，类似微信的语音消息
                else if (message.getCategory() == ChatMessageCategory.AUDIO_FILE) {
                    Log.i("IMAppManager","==> 语音消息");
                }
                //对讲录音，只有开启对讲回放功能，每次有人讲话时，才会把声音录制下来
                else if (message.getCategory() == ChatMessageCategory.PTT_AUDIO_FILE) {
                    Log.i("IMAppManager","==> 对讲录音消息 " + message.getRemote_number() + " "
                            + message.getRemote_name() + " isOut=" + message.getIs_out());
                }
                //视频消息，类似微信的视频消息
                else if (message.getCategory() == ChatMessageCategory.VIDEO_FILE) {
                    Log.i("IMAppManager","==> 视频消息: " + message.getDownload_status() +"-" +message.getHttpFile() +"-" + message.getLocalFile());
                    switch (message.getDownload_status()) {
                        case ChatMessageStatus.File.DOWN_SUCCESSED:
                            message.setDownload_status(ChatMessageStatus.File.DOWN_SUCCESSED);
                            //play
                            break;
                        case ChatMessageStatus.File.DOWN_UNINIT:
                            message.setDownload_status(ChatMessageStatus.File.DOWN_STARTING);
                            message.setLocalFile(null);//接口原来内置了地址   不需要
//                            FileDownloadManager.getInstance().startDownTask(message.getId(), message.getHttpFile(), message.getLocalFile());
                            //使用EventBus监听ChatFileDownloadCompletedEvent，获取文件下载结果
                            break;
                    }
                }
                //图片消息
                else if (message.getCategory() == ChatMessageCategory.IMAGE) {
                    Log.i("IMAppManager","==> 图片消息");
                }
                //位置消息
                else if (message.getCategory() == ChatMessageCategory.LOCATION) {
                    Log.i("IMAppManager","==> 位置消息");
                }
                //文字消息
                else if (message.getCategory() == ChatMessageCategory.TEXT) {
                    Log.i("IMAppManager","==> 文字消息: " + message.getText());
                }

                //================以下两种消息，如果业务需求，可以放到动态页中去=========================
                //拍传@消息
                else if (message.getCategory() == ChatMessageCategory.NOTIFICATION_REPORT) {
                    Log.i("IMAppManager","==> 拍传@消息");
                }
                //报警消息
                else if (message.getCategory() == ChatMessageCategory.ALERT) {
                    Log.i("IMAppManager","==> 报警消息: " + message.getText());
                }
                //任务消息
                else if (message.getCategory() == ChatMessageCategory.NOTIFICATION_TASK) {
                    Log.i("IMAppManager","==> 任务消息: " + message.getText());
                }
                //==================================================================================

                //其它消息一般用不到
                else {
                    Log.i("IMAppManager","==> 其它消息: " + message.getText());
                }
            }
        }

        @Override
        public void onIncoming(IncomingInfo incomingInfo) {
            Log.d(TAG,"onIncoming-> sessionId=" + incomingInfo.sessionId + " type=" + incomingInfo.sessionType + " uid=" +
                    incomingInfo.callerId + " name=" + incomingInfo.callerName + " level=" + incomingInfo.level +
                    " extra=" + incomingInfo.extra);

            // 当前会诊业务模式
            if (CCHelper.isCcBzMode) {
                CCHelper.INSTANCE.handlerCCIncoming(application, incomingInfo);
                return;
            }

            if (incomingInfo.sessionType == SessionType.TYPE_AUDIO_PTT_TEMP || incomingInfo.sessionType == SessionType.TYPE_AUDIO_PTT){
                boolean ret = ICPRtcManager.getsInstance().joinChannel(incomingInfo.callerId);
                if (!ret) {
//                    Toast.makeText(mContext, "接听失败：" + sessionId, Toast.LENGTH_SHORT).show();
                    ICPRtcManager.getsInstance().hangUpCall(incomingInfo.sessionId);
                }
                return;
            }
            if (IMAppManager.this.currentCallInfo != null) {
                // 已有来电，挂断新的
                ICPRtcManager.getsInstance().hangUpCall(incomingInfo.sessionId);
                Toast.makeText(application, "强制挂断新的来电", Toast.LENGTH_SHORT).show();
                return;
            }

            IMAppManager.this.currentCallInfo = incomingInfo;
            if (incomingInfo.sessionType == SessionType.TYPE_VIDEO_MONITOR_CALL) {
                monitorVideoHelper = new MonitorVideoHelper(incomingInfo);
                monitorVideoHelper.handlerIncoming();
//                boolean ret = ICPRtcManager.getsInstance().acceptCall(incomingInfo.sessionId);
//                if (!ret) {
//                    YLogImpl.e(TAG,"视频监控接听失败");
//                    return;
//                }

            } else {
                Log.e("TAG", "onIncoming: "+YLIMConfig.windowManagerChoose);
                if (YLIMConfig.windowManagerChoose){
//                    MeetManger.getInstance().startMeet(application,
//                            incomingInfo.sessionId,
//                            incomingInfo.callerId,
//                            incomingInfo.callerName,
//                            incomingInfo.sessionType,
//                            incomingInfo.extra,
//                            true);
                    if (mYLWebSocketInterface != null){
                        WebModel webModel = mWebModelFactory.createAVResultWebModelIM();
                        webModel.getiMWebModel().getAvResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_AV_IN);
                        webModel.getiMWebModel().getAvResultConfig().setSessionId(incomingInfo.sessionId);
                        webModel.getiMWebModel().getAvResultConfig().setCallerId(incomingInfo.callerId);
                        webModel.getiMWebModel().getAvResultConfig().setTypeCode(incomingInfo.sessionType);
                        webModel.getiMWebModel().getAvResultConfig().setCallerName(incomingInfo.callerName);
                        webModel.getiMWebModel().getAvResultConfig().setExtra(incomingInfo.extra);
                        webModel.getiMWebModel().getAvResultConfig().setIncomingCall(true);
                        String jsonString = new Gson().toJson(webModel);
                        mYLWebSocketInterface.sendMessage(jsonString);
                    }

                    ARouter.getInstance()
                            .build(RouterPath.path.av_pop_activity)
                            .withLong("sessionId", incomingInfo.sessionId)
                            .withString("callerId", incomingInfo.callerId)
                            .withString("callerName", incomingInfo.callerName)
                            .withInt("type", incomingInfo.sessionType)
                            .withString("extra", incomingInfo.extra)
                            .withBoolean("isIncomingCall", true)
                            .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                            .navigation();
                }else{
//                    Intent intent = new Intent(application, AvActivity.class);
//                    intent.putExtra("sessionId", incomingInfo.sessionId);
//                    intent.putExtra("callerId", incomingInfo.callerId);
//                    intent.putExtra("callerName", incomingInfo.callerName);
//                    intent.putExtra("type", incomingInfo.sessionType);
//                    intent.putExtra("extra", incomingInfo.extra);
//                    intent.putExtra("isIncomingCall", true);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    application.startActivity(intent);

                    ARouter.getInstance()
                            .build(RouterPath.path.av_activity)
                            .withLong("sessionId", incomingInfo.sessionId)
                            .withString("callerId", incomingInfo.callerId)
                            .withString("callerName", incomingInfo.callerName)
                            .withInt("type", incomingInfo.sessionType)
                            .withString("extra", incomingInfo.extra)
                            .withBoolean("isIncomingCall", true)
                            .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            .withTransition(com.camera.base.R.anim.slide_in_right, com.camera.base.R.anim.slide_out_left)
                            .navigation();
                }
            }
        }

        @Override
        public void onIgnoreIncoming(int sessionType, long callerId) {
            super.onIgnoreIncoming(sessionType, callerId);
            Log.i(TAG,"onIgnoreIncoming sessionType=" + sessionType + ", callerId=" + callerId);
        }

        @Override
        public void onCallDisconnected(long sessionId, int reason) {
            Log.i(TAG,"onCallDisconnected sessionId=" + sessionId + ", reason=" + reason);
            if (currentCallInfo != null && currentCallInfo.sessionId == sessionId) {
                Log.i(TAG,"onCallDisconnected currentCallInfo=" + currentCallInfo);
                currentCallInfo = null;
            }
        }

        @Override
        public void onChannelChangedEvent(ChannelChangedEvent event) {
            Toast.makeText(application, "onChannelChangedEvent", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onForcedOffline() {
            //True: 响应了下线事件，False：没有响应，sdk内部会弹出对话框，禁止再操作
            Toast.makeText(application, "onForcedOffline", Toast.LENGTH_SHORT).show();
            return false;
        }

        @Override
        public void onBackstageMonitorAction(int action, long sessionId, String monitorUid, boolean isVideoMonitor) {
            Log.i("IMAppManager","onBackstageMonitorAction: action=" + action);
        }

        @Override
        public void onReceiveLocation(double latitude, double longitude, String address) {
            Toast.makeText(application, "坐标变化(" + latitude + "," + longitude + ")", Toast.LENGTH_SHORT).show();
        }


        @Override
        public void onRequestCamera() {
            Log.d("IMAppManager","onRequestCamera");
        }

        @Override
        public void onReleaseCamera() {
            Log.d("IMAppManager","onReleaseCamera");
        }

        @Override
        public void onRequestMic() {
            Log.d("IMAppManager","onRequestMic");
        }

        @Override
        public void onReleaseMic() {
            Log.d("IMAppManager","onReleaseMic");
        }

        @Override
        public void onVideoStreamTakePictureFinish(String filePath) {
            Toast.makeText(application, "拍照已保存到: " + filePath, Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onPttIdle() {
            //对讲组当前空闲，无人讲话
            if (mYLWebSocketInterface != null) {
                speakWebModel = mWebModelFactory.createResultWebModelIM("apply_ptt_result");
                speakWebModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_APPLY_PTT);
                speakWebModel.getiMWebModel().getImResultConfig().setSpeak(2);
                String jsonString = new Gson().toJson(speakWebModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }
        }

        @Override
        public void onPttRequesting() {
            //本机正在申请话语权
            if (mYLWebSocketInterface != null) {
                speakWebModel = mWebModelFactory.createResultWebModelIM("apply_ptt_result");
                speakWebModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_APPLY_PTT);
                speakWebModel.getiMWebModel().getImResultConfig().setSpeak(0);
                String jsonString = new Gson().toJson(speakWebModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }
        }

        @Override
        public void onPttKicked() {
            //自己讲话时，话语权被抢
            if (mYLWebSocketInterface != null) {
                speakWebModel = mWebModelFactory.createResultWebModelIM("apply_ptt_result");
                speakWebModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_APPLY_PTT);
                speakWebModel.getiMWebModel().getImResultConfig().setSpeak(3);
                String jsonString = new Gson().toJson(speakWebModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }
        }
        @Override
        public void onPttTalking(boolean isRemote, String uid, int total, long fromChannelNumber) {
            //申请话语权成功，开始讲话
            YLogImpl.d(TAG, "onPttTalking:"+isRemote);
            if (isRemote){
                if (mYLWebSocketInterface != null) {
                    speakWebModel = mWebModelFactory.createResultWebModelIM("apply_ptt_result");
                    speakWebModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_APPLY_PTT);
                    speakWebModel.getiMWebModel().getImResultConfig().setSpeak(5);

                    User user = ICPRtcManager.getsInstance().getUser(uid);
                    String name = user != null ? user.getName() : uid;
                    String tips = name + " 正在讲话";

                    ArrayList users = new ArrayList<User>();
                    users.add(user);
                    speakWebModel.getiMWebModel().getImResultConfig().setUsers(users);

                    String jsonString = new Gson().toJson(speakWebModel);
                    mYLWebSocketInterface.sendMessage(jsonString);
                }
            }else{
                if (mYLWebSocketInterface != null) {
                    speakWebModel = mWebModelFactory.createResultWebModelIM("apply_ptt_result");
                    speakWebModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_APPLY_PTT);
                    speakWebModel.getiMWebModel().getImResultConfig().setSpeak(1);
                    String jsonString = new Gson().toJson(speakWebModel);
                    mYLWebSocketInterface.sendMessage(jsonString);
                }
            }
        }
        @Override
        public void onPttError(int code) {
            //发生错误，收到该回调时，恢复UI
            if (mYLWebSocketInterface != null) {
                speakWebModel = mWebModelFactory.createResultWebModelIM("apply_ptt_result");
                speakWebModel.getiMWebModel().getImResultConfig().setCode(WebSocketCode.IM_RESULT_CODE_APPLY_PTT);
                speakWebModel.getiMWebModel().getImResultConfig().setSpeak(4);
                String jsonString = new Gson().toJson(speakWebModel);
                mYLWebSocketInterface.sendMessage(jsonString);
            }
        }
    };
    @Override
    public void uploadFile(@NotNull String localFilePath, int fileType, @NotNull FileUploadListener listener) {
        ICPRtcManager.getsInstance().uploadFile(localFilePath, fileType, new OnFileUploadListener() {
            @Override
            public void onUploadSucceed(String s, String s1) {
                //成功
                listener.onUploadSucceed(s,s1);
            }

            @Override
            public void onUploadFailed(String s) {
                //失败
                listener.onUploadFailed(s);
            }

            @Override
            public void onUploadProgress(int i) {
                //
                listener.onUploadProgress(i);
            }
        });
    }
}
